package com.itheima.day16.reflect.test5;

import java.lang.reflect.Field;

//        Field类用于给成员变量赋值的方法
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
//        void set(Object obj, Object value)	赋值
//        Object get(Object obj)            	获取值
        // method1();
        // method2();
        // method3();


    }

    private static void method3() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        // 1.获取class对象
        Class<?> className = Class.forName("com.itheima.day16.reflect.test5.Student");

        // 2.获取money私有成员变量的Fiele对象
        Field field = className.getDeclaredField("money");

        // 3.取消访问权限
        field.setAccessible(true);

        // 4.创建类对象
        Student student = (Student) className.newInstance();

        // 5.利用get方法获取值
        int money = (int) field.get(student);

        // 6.打印
        System.out.println(money);
    }

    private static void method2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        // 1.获取class对象
        Class<?> className = Class.forName("com.itheima.day16.reflect.test5.Student");

        // 2.获取money私有成员变量的Field对象
        Field field = className.getDeclaredField("money");

        // 3.取消访问检查
        field.setAccessible(true);

        // 4.利用set方法进行赋值
        // 4.1创建类对象
        Student student = (Student) className.newInstance();
        // 4.2赋值
        field.set(student,8888);

        // 5.打印
        System.out.println(student);
    }

    private static void method1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        // 1.获取class对象
        Class<?> className = Class.forName("com.itheima.day16.reflect.test5.Student");

        // 2.获取name公共成员变量的Field对象
        Field field = className.getField("name");

        // 3.利用set方法进行赋值
        // 3.1创建类对象
        Student student = (Student) className.newInstance();
        // 3.2赋值
        field.set(student,"张帆");

        // 打印对象
        System.out.println(student);
    }
}
